package com.lc.reader.ui.fragment

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.google.android.material.snackbar.Snackbar
import com.lc.reader.R
import com.lc.reader.databinding.FragmentBookshelfBinding
import com.lc.reader.ui.adapter.BookAdapter
import com.lc.reader.data.model.Book
import androidx.navigation.fragment.findNavController
import kotlinx.coroutines.launch
import java.io.File
import android.content.Context
import androidx.appcompat.app.AlertDialog
import com.lc.reader.di.DependencyContainer
import com.lc.reader.data.repository.BookRepository
import kotlinx.coroutines.flow.collectLatest

class BookshelfFragment : Fragment() {
    
    private var _binding: FragmentBookshelfBinding? = null
    private val binding get() = _binding!!
    
    private lateinit var bookAdapter: BookAdapter
    private lateinit var bookRepository: BookRepository
    
    private val selectBookLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val uri = result.data?.data
            if (uri != null) {
                importBook(uri)
            }
        }
    }
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentBookshelfBinding.inflate(inflater, container, false)
        return binding.root
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        // 初始化Repository
        bookRepository = DependencyContainer.getBookRepository(requireContext())
        
        setupRecyclerView()
        setupObservers()
        setupClickListeners()
    }
    
    private fun setupRecyclerView() {
        bookAdapter = BookAdapter(
            onBookClick = { book ->
                // 点击书籍进入阅读界面
                navigateToReader(book)
            },
            onBookDelete = { book ->
                // 删除书籍
                showDeleteConfirmation(book)
            }
        )
        
        binding.recyclerViewBooks.apply {
            layoutManager = GridLayoutManager(context, 3)
            adapter = bookAdapter
        }
    }
    
    private fun setupObservers() {
        // 观察数据库中的书籍变化
        lifecycleScope.launch {
            bookRepository.getAllBooks().collectLatest { books ->
                updateBooksDisplay(books)
            }
        }
    }
    
    private fun setupClickListeners() {
        binding.fabAddBook.setOnClickListener {
            openFilePicker()
        }
    }
    
    private fun updateBooksDisplay(books: List<Book>) {
        if (books.isEmpty()) {
            binding.emptyState.visibility = View.VISIBLE
            binding.recyclerViewBooks.visibility = View.GONE
        } else {
            binding.emptyState.visibility = View.GONE
            binding.recyclerViewBooks.visibility = View.VISIBLE
            
            // 为每本书加载阅读进度并创建新的Book对象
            val updatedBooks = books.map { book ->
                loadReadingProgress(book)
            }
            
            bookAdapter.submitList(updatedBooks)
        }
    }
    
    private fun loadReadingProgress(book: Book): Book {
        val sharedPrefs = requireContext().getSharedPreferences("reading_progress", Context.MODE_PRIVATE)
        val currentPage = sharedPrefs.getInt("book_${book.id}_page", 0)
        val lastReadTime = sharedPrefs.getLong("book_${book.id}_time", 0L)
        
        // 创建新的Book对象，包含更新后的阅读进度
        return book.copy(
            currentPage = currentPage,
            lastReadTime = lastReadTime,
            readingProgress = if (book.totalPages > 0) currentPage.toFloat() / book.totalPages else 0f
        )
    }
    
    private fun openFilePicker() {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
            addCategory(Intent.CATEGORY_OPENABLE)
            type = "*/*"
            // 关键：授予一次性和可持久化读取权限
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
        }
        selectBookLauncher.launch(intent)
    }

    private fun importBook(uri: Uri) {
        lifecycleScope.launch {
            try {
                // 获取并持久化授权（如果系统返回了可持久化标志）
                val flags = (Intent.FLAG_GRANT_READ_URI_PERMISSION)
                try {
                    requireContext().contentResolver.takePersistableUriPermission(uri, flags)
                } catch (_: SecurityException) { /* 某些来源可能不支持持久化，忽略 */ }

                val fileName = getFileNameFromUri(uri)
                val fileSize = getFileSizeFromUri(uri)
                val format = getFileFormat(fileName)

                // 保存URI字符串即可，后续用ContentResolver读取
                val book = Book(
                    title = fileName,
                    author = "未知作者",
                    filePath = uri.toString(),
                    fileSize = fileSize,
                    format = format.uppercase(),
                    totalPages = 0,
                    readingProgress = 0f
                )

                bookRepository.insertBook(book)
                Snackbar.make(binding.root, "《$fileName》导入成功", Snackbar.LENGTH_SHORT).show()
            } catch (e: Exception) {
                Snackbar.make(binding.root, "导入失败: ${e.message}", Snackbar.LENGTH_SHORT).show()
            }
        }
    }
    
    private fun getFileNameFromUri(uri: Uri): String {
        return try {
            val cursor = requireContext().contentResolver.query(uri, null, null, null, null)
            cursor?.use {
                if (it.moveToFirst()) {
                    val displayNameIndex = it.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)
                    if (displayNameIndex != -1) {
                        it.getString(displayNameIndex)
                    } else {
                        uri.lastPathSegment ?: "未知文件"
                    }
                } else {
                    uri.lastPathSegment ?: "未知文件"
                }
            } ?: (uri.lastPathSegment ?: "未知文件")
        } catch (e: Exception) {
            uri.lastPathSegment ?: "未知文件"
        }
    }
    
    private fun getFileSizeFromUri(uri: Uri): Long {
        return try {
            val cursor = requireContext().contentResolver.query(uri, null, null, null, null)
            cursor?.use {
                if (it.moveToFirst()) {
                    val sizeIndex = it.getColumnIndex(android.provider.OpenableColumns.SIZE)
                    if (sizeIndex != -1) {
                        it.getLong(sizeIndex)
                    } else {
                        0L
                    }
                } else {
                    0L
                }
            } ?: 0L
        } catch (e: Exception) {
            0L
        }
    }
    
    private fun getFileFormat(fileName: String): String {
        return fileName.substringAfterLast('.', "").lowercase()
    }
    
    private fun navigateToReader(book: Book) {
        // 使用Navigation组件进行导航，传递完整的书籍信息
        val bundle = Bundle().apply {
            putLong("bookId", book.id)
            putString("bookTitle", book.title)
            putString("bookAuthor", book.author)
            putString("bookFilePath", book.filePath)
            putString("bookFormat", book.format)
        }
        findNavController().navigate(R.id.readerFragment, bundle)
    }
    
    private fun showDeleteConfirmation(book: Book) {
        AlertDialog.Builder(requireContext())
            .setTitle("删除书籍")
            .setMessage("确定要删除《${book.title}》吗？此操作不可撤销。")
            .setPositiveButton("删除") { _, _ ->
                deleteBook(book)
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    private fun deleteBook(book: Book) {
        lifecycleScope.launch {
            try {
                // 从数据库中删除书籍
                bookRepository.deleteBook(book)
                
                // 清除相关的阅读进度和书签
                clearBookData(book.id)
                
                // 显示删除成功提示
                Snackbar.make(binding.root, "《${book.title}》已删除", Snackbar.LENGTH_SHORT).show()
            } catch (e: Exception) {
                Snackbar.make(binding.root, "删除失败: ${e.message}", Snackbar.LENGTH_SHORT).show()
            }
        }
    }
    
    private fun clearBookData(bookId: Long) {
        val sharedPrefs = requireContext().getSharedPreferences("reading_progress", Context.MODE_PRIVATE)
        val bookmarksPrefs = requireContext().getSharedPreferences("bookmarks", Context.MODE_PRIVATE)
        
        // 清除阅读进度
        sharedPrefs.edit().apply {
            remove("book_${bookId}_page")
            remove("book_${bookId}_time")
            apply()
        }
        
        // 清除书签
        bookmarksPrefs.edit().apply {
            remove("book_${bookId}")
            apply()
        }
    }
    
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
